package com.zy.multiredis.config;

import java.util.Map;
import java.util.Set;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.zy.multiredis.util.MultiRedisInfoHolder;

@Component
public class MultiRedisTemplateInitalPostProcessors implements InstantiationAwareBeanPostProcessor, BeanFactoryAware {

    private ConfigurableListableBeanFactory beanFactory;

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
        throws BeansException {
        if (bean instanceof RedisTemplate) {
            Map<String, RedisProperties> multiRedisInfos = MultiRedisInfoHolder.getmultiRedisInfos();
            Set<String> beanNames = multiRedisInfos.keySet();
            if (beanNames.contains(beanName) && beanFactory.getBeanDefinition(beanName).getAttribute("auto") != null) {
                RedisTemplate redisTemplate = (RedisTemplate)bean;
                redisTemplate.setConnectionFactory(beanFactory.getBean(MultiRedisConnectionFactoryMap.class)
                    .getRedisConnectionFactories().get(beanName));
            }
        }
        return pvs;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = (ConfigurableListableBeanFactory)beanFactory;
    }
}
